package com.ibangnuo.manage.service.shop;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ibangnuo.framework.domain.*;
import com.ibangnuo.framework.domain.request.shop.ShopRequest;
import com.ibangnuo.framework.model.response.CommonCode;
import com.ibangnuo.framework.model.response.ObjectResult;
import com.ibangnuo.framework.model.response.QueryResponseResult;
import com.ibangnuo.framework.model.response.QueryResult;
import com.ibangnuo.framework.utils.MD5Utils;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;
import com.ibangnuo.manage.dao.employee.AgentRepository;
import com.ibangnuo.manage.dao.employee.CommercialMapper;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import com.ibangnuo.manage.dao.employee.EmployeeRepository;
import com.ibangnuo.manage.dao.shop.MerchantsMapper;
import com.ibangnuo.manage.dao.shop.MerchantsRepository;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author:ly
 * @Data:2019/12/31 14:09
 * @Verdion:1.0
 */
@Service
public class MerchantsService {

    private static Logger LOGGER = LoggerFactory.getLogger(MerchantsService.class);
    @Autowired
    private MerchantsRepository merchantsRepository;
    @Autowired
    private MerchantsMapper merchantsMapper;
    @Autowired
    private CommercialMapper commercialMapper;
    @Autowired
    private  CommercialRepository commercialRepository;

    @Autowired
    private AgentRepository agentRepository;
    @Autowired
    private EmployeeRepository employeeRepository;

    /**
     * 门店查询
     * 1.获取当前用户userid
     * 2.获取登陆者的id
     *  管理员
     *  代理商
     *     查该门下的所有商户的门店
     *  员工
     *     查该员工的所有的商户的门店
     *
     * @param employeeRequest
     * @return
     */
    public QueryResponseResult query(Map employeeRequest) {

        LOGGER.info("门店查询参数:{}", employeeRequest.toString());

        if (employeeRequest == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        Integer page = (Integer) employeeRequest.get("page");
        Integer size = (Integer) employeeRequest.get("limit");
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 20;
        }
        PageHelper.startPage(page, size);
        QueryResult queryResult = new QueryResult();
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        //String loginCId = user1.getCommercialTenantId();
        if (user1.getType() == 0) { //管理员查询

        } else if (user1.getType() == 1) { //代理商查询
            String userId = user1.getId();
            Agent agent = agentRepository.findByUserId(userId);
            employeeRequest.put("aId", agent.getId());
        } else if(user1.getType()== 2) {  //商户查询
            String userId = user1.getId();
            CommercialTenant commercialTenant = commercialMapper.findByUserId(userId);
            String loginCId = commercialTenant.getId();
            employeeRequest.put("cId", loginCId);
        }else if (user1.getType()==4){  //员工查询
            String userId = user1.getId();
            Employee employee = employeeRepository.findByUserId(userId);
            List<CommercialTenant> byEmployeeId = commercialRepository.findByEmployeeId(employee.getId());//所有商户
            List<String> list =new ArrayList<>();
            for (CommercialTenant commercialTenant : byEmployeeId) {
                list.add(commercialTenant.getId());
            }
            if (list!=null && list.size()>0) {
                employeeRequest.put("list", list);
            }else{
                queryResult.setList(null);
                queryResult.setTotal(0);
                return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
            }

        }
        List<Map> all = merchantsMapper.query(employeeRequest);
        if (all.size()>0 && all!=null) {
            for (Map map : all) {
                Integer merchantsStatus = (Integer) map.get("merchantsStatus");
                if (merchantsStatus == 0) {
                    map.put("merchantsStatus", "锁定");
                } else {
                    map.put("merchantsStatus", "正常");
                }
            }
            PageInfo<Map> pageInfo = new PageInfo<Map>(all);
            queryResult.setList(pageInfo.getList());
            queryResult.setTotal(pageInfo.getTotal());
            return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        } else{
            queryResult.setList(null);
            queryResult.setTotal(0);
            return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        }
    }

    /**
     * 门店添加
     * 1.获取当前用户userid
     * 2.获取商户id
     * 3.添加门店信息
     *
     * @param map
     * @return
     */
    public QueryResponseResult addMerchants(Map map) {
        LOGGER.info("门店添加的参数:{}", map);
        if (map == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        String userId = user1.getId();
        Merchants m = new Merchants();
        String cId="";//商户id
        String agentId="";//代理商id
        if (map.get("agentIdAgentId").toString()!=null && map.get("agentIdAgentId").toString()!=""){
           cId  = map.get("agentIdAgentId").toString();//商户id
            Optional<CommercialTenant> byId = commercialRepository.findById(cId);//商户信息
            if (byId.isPresent()){
               agentId  = byId.get().getAgentId();//代理行id
            }
        }
        if (user1.getType() == 0 ) {
            //管理员添加门店
            m.setCommercialTenantId(cId);
            m.setAgentID(agentId);
        }else if (user1.getType()==1){
            //代理商添加门店
            m.setAgentID(agentId);
            m.setCommercialTenantId(cId);
        }else{
            CommercialTenant commercialTenant = commercialMapper.findByUserId(userId);
            String loginCId = commercialTenant.getId();
            m.setCommercialTenantId(loginCId);
            m.setAgentID(agentId);
        }

        Map map1 = (Map) map.get("imageList");
        String jsonString = JSONObject.toJSONString(map1);
        m.setUrl(jsonString);
        m.setAddress((String) map.get("merchantsAddress"));
        long nextId = PrimaryKeyUtil.nextId();
        String number = Long.toString(nextId);
        m.setNumber(number);
        m.setCreateTime(new Date());
        UUID uuid = UUID.randomUUID();
        String id = uuid.toString().replace("-", "");
        m.setId(id);

        m.setIsDelete(1);
        m.setStatus(1);
        m.setName((String) map.get("merchantsName"));
        m.setUpdateTime(new Date());
        merchantsRepository.save(m);
        return new QueryResponseResult(CommonCode.SUCCESS, null);
    }

    /**
     * 门店删除
     * 1.根据门店id删除门店
     *
     * @param merchantsUuid
     * @return
     */
    public QueryResponseResult delMerchants(String merchantsUuid) {
        LOGGER.info("门店删除的参数:{}", merchantsUuid);
        Optional<Merchants> byId = merchantsRepository.findById(merchantsUuid);
        Merchants merchants = byId.get();
        merchants.setIsDelete(0);
        merchantsRepository.save(merchants);
        return new QueryResponseResult(CommonCode.SUCCESS, null);
    }

    /**
     * 门店信息回显
     * 1.根据门店id
     *
     * @param id
     * @return
     */
    public QueryResponseResult findById(String id) {
        LOGGER.info("门店查询的参数:{}", id);
        if (id == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        QueryResult queryResult = new QueryResult();
        List<Map> all = merchantsMapper.findById(id);
        //List<Map> all = employeeMapper.queryById(id);
        if (all.size() > 0 && all != null) {
            queryResult.setList(all);
            queryResult.setTotal(all.size());
            return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        }
        return new QueryResponseResult(CommonCode.FAIL, null);

    }


    /**
     * 门店编辑
     * 1.根据门店id查询门店的基本信息
     * 2.更新门店信息
     *
     * @param map
     * @return
     */
    public QueryResponseResult upMerchants(Map map) {


        LOGGER.info("编辑门店的信息:{}", map.toString());
        if (map == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        String merchantsUuid = (String) map.get("merchantsUuid");
        Merchants merchants = merchantsRepository.findById(merchantsUuid).get();
        String merchantsNumber = (String) map.get("merchantsNumber");
        merchants.setNumber(merchantsNumber);
        String merchantsName = (String) map.get("merchantsName");
        merchants.setName(merchantsName);
        // Date merchantsCreateTime = (Date) map.get("merchantsCreateTime");
        merchants.setUpdateTime(new Date());
        String merchantsStatus = (String) map.get("merchantsStatus");
        int status = Integer.parseInt(merchantsStatus);
        merchants.setStatus(status);
        String merchantsAddress = (String) map.get("merchantsAddress");
        merchants.setAddress(merchantsAddress);
        merchantsRepository.save(merchants);
        return new QueryResponseResult(CommonCode.SUCCESS, null);
    }

    /**
     * 门店名称查询

     * @return
     */
    public QueryResponseResult selectShopName() {
        List<Merchants> all = merchantsRepository.findAll();
        QueryResult queryResult = new QueryResult();
        queryResult.setList(all);
        queryResult.setTotal(all.size());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);

    }

    /**
     * 多门店添加新版
     * 1.执行删除操作
     * 2.进行保存
     * @param shopRequest
     * @return
     */
    public ObjectResult addNew(ShopRequest shopRequest){
        if(shopRequest ==null){
            return new ObjectResult(CommonCode.FAIL,null);
        }
        List<Merchants> list = merchantsRepository.findAllByCommercialTenantId(shopRequest.getCommercialTenantId());
        merchantsRepository.deleteInBatch(list);
        for (Map<String, Object> map : shopRequest.getShops()) {
            Merchants merchants = new Merchants();
            merchants.setCommercialTenantId(shopRequest.getCommercialTenantId());
            merchants.setCreateTime(new Date());
            merchants.setAddress(String.valueOf(map.get("address")));
            merchants.setName(String.valueOf(map.get("name")));
            merchants.setIsDelete(1);
            merchants.setNumber(PrimaryKeyUtil.nextId()+"");
            merchants.setStatus(1);
            merchants.setUpdateTime(new Date());
            merchantsRepository.save(merchants);

        }
        Map<String,Object> map = new HashMap<>();
        map.put("id",shopRequest.getCommercialTenantId());
        return new ObjectResult(CommonCode.SUCCESS,map);

    }

    /**
     * 依据商家id查询门店
     * @param commercialId
     * @return
     */
    public ObjectResult findByCommercialIdNew(String commercialId){
        List<Merchants> list = merchantsRepository.findAllByCommercialTenantId(commercialId);
        return new ObjectResult(CommonCode.SUCCESS,list);
    }
}
